import fetch from 'isomorphic-fetch';
import { notification } from 'antd';
import cookie from 'js-cookie';

const errorMessages = (res) => `${res.status} ${res.statusText}`;

function check401(res) {
  if (res.status === 401) {
    alert(res.status)
    location.href = '/401';
  }
  return res;
}

function check404(res) {
  if (res.status === 404) {
    // open404Notification('error');
    notification['error']({
      message: '无法找到服务',
      description: '状态码：404',
    })
  }
  return res;
}

function check500(res) {
  if (res.status === 500) {
    // open500Notification('error');
    notification['error']({
      message: '内部服务器错误',
      description: '状态码：500',
    })
  }
  return res;
}

function jsonParse(res) {
  return res.json().then(jsonResult => ({...res, jsonResult}));
  // return res.json();
}

function errorMessageParse(res) {
  const {success, message} = res.jsonResult;
  if (!success) {
    return Promise.reject(message);
  }
  return res;
}

function xFetch(url, options) {
  const opts = {...options};
  opts.headers = {
    ...opts.headers,
    // authorization: cookie.get('authorization') || '',
  };

  return fetch(url, opts)
    // .then(check401)
    .then(check404)
    .then(check500);
    // .then(jsonParse)
    // .then(errorMessageParse);
}

export default xFetch;
